package com.lizard.schedule.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.lizard.schedule.log.ScheduleLog;
import com.lizard.schedule.manager.AccountManager;
import com.lizard.schedule.manager.observer.ObserverIfaces;
import com.lizard.schedule.manager.observer.ObserverManager;
import com.lizard.schedule.persistence.db.bean.Schedule;
import com.lizard.schedule.persistence.db.table.ScheduleTbl;
import com.lizard.schedule.ui.adapter.schedule.ScheduleListAdapter;
import com.lizard.schedule.ui.activity.base.BaseActivity;
import com.lizard.schedule.ui.fragment.MyScheduleFragment;
import com.lizard.schedule.ui.view.Titlebar;
import com.lizard.schedule.ui.view.schedulelist.ScheduleListView;
import com.lizard.schedule.R;
import com.lizard.schedule.utils.StatusBarUtil;

import java.util.List;
import java.util.Map;

/**
 * 历史计划页
 */
public class HistoryActivity extends BaseActivity implements OnScrollListener,
        ObserverIfaces.UpdateScheduleToUi,
        ObserverIfaces.SyncListener {

    private final String TAG = HistoryActivity.class.getSimpleName();

    private ScheduleListView mScheduleList;

    private ScheduleListAdapter mScheduleListAdapter;

    private View mHistoryNone;

    private Titlebar mTitlebar;

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();

        // 设置状态栏颜色
        StatusBarUtil.setStatusBarColor(this, R.color.schedule_blue);

        setContentView(R.layout.a_history);
        registObservers();
        initView();
        loadMore();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initView(){
        mHistoryNone = findViewById(R.id.history_none);
        initTitle();
        initScheduleList();
    }

    private void initTitle(){
        mTitlebar =  (Titlebar) findViewById(R.id.title_bar);
        mTitlebar.setLeftBtnClk(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
        mTitlebar.setOnDoubleClickListener(new Titlebar.OnDoubleClickListener() {
            @Override
            public void onDobuleClick() {
                scrollToTop();
            }
        });
    }

    private void initScheduleList(){
        mScheduleList = (ScheduleListView) findViewById(R.id.history_schedule_list);
        mScheduleList.setMode(PullToRefreshBase.Mode.DISABLED);
        mScheduleList.setOnScrollListener(this);

        mScheduleListAdapter = new ScheduleListAdapter(this, mScheduleList, ScheduleListAdapter.SORT_BY_HISTORY);
        mScheduleList.setAdapter(mScheduleListAdapter);
        mScheduleList.setOnItemClickListener(mScheduleListAdapter);
    }

    /**
     * 数据库加载数据
     */
    private void loadMore(){
        loadMore(MyScheduleFragment.PAGE_SIZE);
    }

    /**
     * 数据库加载数据
     *
     * @param size
     */
    private void loadMore(int size){

        Schedule lastData = mScheduleListAdapter.getLastSchedule();

        List<Schedule> schedules = ScheduleTbl.getInstance().select(
                AccountManager.getInstance().getmUsernameMD5L16(),
                lastData == null ? 0 : lastData.getLocalId(),
                size,
                lastData == null ? System.currentTimeMillis() : lastData.getBeginTime(),
                false,
                false
        );

        mScheduleListAdapter.addData(schedules);
        setScheduleListViewVisibility();
    }

    /**
     * 计划列表滑到顶部
     */
    public void scrollToTop(){
        mScheduleList.getRefreshableView().smoothScrollToPosition(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregistObservers();
    }

    /**
     * 注册观察者通知
     */
    private void registObservers(){
        ObserverManager.getInstance().registerUpdateScheduleToUi(this);
        ObserverManager.getInstance().registerSyncListener(this);
    }

    /**
     * 注销观察者通知
     */
    private void unregistObservers(){
        ObserverManager.getInstance().unregisterUpdateScheduleToUi(this);
        ObserverManager.getInstance().unregisterSyncListener(this);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {}

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if(totalItemCount > MyScheduleFragment.PAGE_SIZE){
            if ((firstVisibleItem + visibleItemCount == totalItemCount) && (totalItemCount != 0)) {
                // 滑动到底部
                ScheduleLog.v(TAG, "scorll to bottom then load more...");
                loadMore();
            }
        }
    }

    @Override
    public void update(Schedule schedule) {
        if (schedule.getBeginTime() < System.currentTimeMillis()
                && !schedule.isDeleted()) {

            boolean needUpdateToAdapter = true;

            Schedule lastData = mScheduleListAdapter.getLastSchedule();


            if (lastData != null
                    && (schedule.getBeginTime() < lastData.getBeginTime()
                    || (schedule.getBeginTime() == lastData.getBeginTime() && schedule.getLocalId() < lastData.getLocalId()))
                    && mScheduleListAdapter.getCount() >= MyScheduleFragment.PAGE_SIZE) {
                // 这种情况 可能有数据库中的数据存在两者之间 因此选择不添加到界面 等用户滑到底部加载更多
                needUpdateToAdapter = false;
            }

            if (needUpdateToAdapter) {
                if(mScheduleListAdapter.existData(schedule.getLocalId())){
                    // 更新到界面
                    mScheduleListAdapter.updateData(schedule);
                } else{
                    // 界面上不存在该条记录，追加到界面
                    mScheduleListAdapter.addData(schedule);
                    setScheduleListViewVisibility();
                }
            } else{
                mScheduleListAdapter.removeData(schedule.getLocalId());
                setScheduleListViewVisibility();
            }
        } else{
            mScheduleListAdapter.removeData(schedule.getLocalId());
            setScheduleListViewVisibility();
        }
    }

    /**
     * 设置计划listview和无数据提示的显示
     */
    private void setScheduleListViewVisibility(){
        if(mScheduleListAdapter.getCount() > 0){
            mScheduleList.setVisibility(View.VISIBLE);
            mHistoryNone.setVisibility(View.GONE);
        } else{
            mScheduleList.setVisibility(View.GONE);
            mHistoryNone.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        back();
    }

    /**
     * 返回
     */
    private void back(){
        ObserverManager.getInstance().notifyReloadUnfinishedHistoryScheduleCounts();
        finish();
    }

    @Override
    public void netWorkError() {
        // do noting
    }

    @Override
    public void noSync() {
        // do noting
    }

    @Override
    public void syncSuccess(List<Integer> submitedLocalIds, Map<Integer, Long> addedServerIds) {
        mScheduleListAdapter.setSubmitedAndServerIdWithoutNotify(submitedLocalIds, addedServerIds);
    }

    @Override
    public void newData(List<Schedule> addList, List<Schedule> updateList, List<Schedule> deleteList) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                int size = mScheduleListAdapter.getCount();
                if (size < MyScheduleFragment.PAGE_SIZE) {
                    size = MyScheduleFragment.PAGE_SIZE;
                }
                mScheduleListAdapter.clearWithOutNotify();
                loadMore(size);
            }
        });
    }

    @Override
    public void responseFailed(String returnCode) {
        // do noting
    }
}
